global root_dir = "`1'"

include "$root_dir/code/config/config.do"


cap noi log using ${log_dir}/merge_firms.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"
capture noi {


* This do-file merges Orbis firms (based on if they have the same normalized name) 
*and links them to the same set of patents via a common BvD identifier. 


import delimited using ${commondata_dir}/orbis_patents/firm_merge_map.csv, varnames(1) clear
ren bvdid_source BvDIDnumber
tempfile f
save `f'

use ${commondata_dir}/orbis_patents/Orbis_patents_list_2017.dta, clear
mmerge BvDIDnumber using `f', unmatched(master)

*remap BvDID
replace BvDIDnumber = bvdid_target if _m == 3
drop bvdid_target _m

duplicates drop BvDIDnumber appln_id appln_date, force

save ${dataset_dir}/patstat_orbis/Orbis_patents_list_2017_merged.dta, replace

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat